package com.tyqx.biz.controller.eth.scheduler;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tyqx.apiutil.common.GetUrlUtil;
import com.tyqx.bean.model.EthIncomeList;
import com.tyqx.bean.model.EthPoolInfo;
import com.tyqx.bean.model.UserHashrateInfo;
import com.tyqx.bean.model.UserHashrateVo;
import com.tyqx.service.EthIncomeListService;
import com.tyqx.service.EthPoolInfoService;
import com.tyqx.service.UserHashrateInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class SchedulerEthInfoByDay {

    private static final Logger logger = LoggerFactory.getLogger(SchedulerEthInfoByDay.class);


    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private EthPoolInfoService ethPoolInfoService;

    @Resource
    private EthIncomeListService ethIncomeListServic;

    @Resource
    private UserHashrateInfoService userHashrateInfoService;


    ///@Async
    //表示每隔秒
//    @Scheduled(fixedRate = 60 * 1000 * 10)
    @Scheduled(cron = "0 30 8 * * *")
    public void testTasks() throws Exception {
        logger.debug("每天的任务收益记录（定时器启动）");
        try {
            Date currentDate = new Date();

            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


            currentDate = dateFormat.parse(dateFormat.format(currentDate));

            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(currentDate);
            rightNow.add(Calendar.DAY_OF_YEAR,-1);//日期减1天



            Date startDate=dateFormat.parse(dateFormat.format(rightNow.getTime()));

            Date endDate = dateFormat.parse(dateFormat.format(currentDate));


            //昨天
            List<EthPoolInfo> ethPoolInfoList = ethPoolInfoService.selectEthPoolInfoByStartDateToEndDate(startDate,endDate);


            Long startBlock = ethPoolInfoList.get(0).getBlock();
            Long endBlock = ethPoolInfoList.get(ethPoolInfoList.size()-1).getBlock();

            //过去24小时总区块
            Long blockCount =  endBlock - startBlock + 1;

            //过去24小时总奖励
            Double rewardCount = new Double(0);


            //过去24小时总算力
            Double hashRateCount = new Double(0);


            for (int i=0;i<ethPoolInfoList.size();i++){
                EthPoolInfo ethPoolInfo = ethPoolInfoList.get(i);
                hashRateCount = hashRateCount + ethPoolInfo.getHashRate();
                rewardCount = rewardCount + ethPoolInfo.getReward();
            }


            RestTemplate restTemplate = new RestTemplate();
            Map<String,String> params = new HashMap<>();
            String address = "0x62dD3a1d95DB1E4BeD53001291BF04c3f689B515";
            params.put("address",address);

            String url ="https://etherchain.org/api/basic_stats";
            String param="";
            String basicStats = GetUrlUtil.GetUrl(url, param);
            JSONObject basicStatsJson = JSON.parseObject(basicStats);
            JSONObject currentStats = basicStatsJson.getJSONObject("currentStats");

            //当前eth全网平均算力
            BigDecimal currentHashrate = currentStats.getBigDecimal("hashrate");


            //当前区块平均难度
            BigDecimal currentDifficulty = currentStats.getBigDecimal("difficulty");

//            ResponseEntity<String> forEntity = restTemplate.getForEntity("https://api.f2pool.com/eth/{address}", String.class, params);
//            String body = forEntity.getBody();
//            JSONObject f2poolRturnTransactionData = JSON.parseObject(body);
//
//            JSONArray workers = f2poolRturnTransactionData.getJSONArray("workers");
//
//            BigDecimal hash24Count  = new BigDecimal(0);
//            for (int i=0;i<workers.size();i++){
//                JSONArray worker = workers.getJSONArray(i);
//                hash24Count = hash24Count.add(worker.getBigDecimal(4));
//            }
//            hash24Count = hash24Count.movePointLeft(9);
//            BigDecimal daySeconds = new BigDecimal(24*60*60);
//            BigDecimal hash24AvgCount = hash24Count.divide(daySeconds,8, BigDecimal.ROUND_HALF_UP);

            List<UserHashrateVo> userHashrateVoList = new ArrayList<>();
            List<UserHashrateInfo> userHashrateInfoList = userHashrateInfoService.selectUserHashrateInfos();

            for (int i=0;i<userHashrateInfoList.size();i++){
                UserHashrateInfo userHashrateInfo = userHashrateInfoList.get(i);
                UserHashrateVo userHashrateVo1 = new UserHashrateVo();
                userHashrateVo1.setUserCode(userHashrateInfo.getUserCode());
                userHashrateVo1.setHashrate(new BigDecimal(userHashrateInfo.getHashrateAvg()).setScale(8,BigDecimal.ROUND_HALF_UP));
                userHashrateVoList.add(userHashrateVo1);
            }

            //平均算力hash/s 转gh/s
            currentHashrate = currentHashrate.movePointLeft(9);

           for (int j=0;j<userHashrateVoList.size();j++){
               UserHashrateVo userHashrateVo2 = userHashrateVoList.get(j);
               String userCode = userHashrateVo2.getUserCode();
               BigDecimal hashrate = userHashrateVo2.getHashrate();



               //算力比例
               BigDecimal computingPowerRatio = hashrate.divide(currentHashrate,10, BigDecimal.ROUND_HALF_UP);

               //昨日收益
               BigDecimal todayPaid = computingPowerRatio.multiply(BigDecimal.valueOf(rewardCount));

               todayPaid = todayPaid.multiply(new BigDecimal(0.97));

               todayPaid = todayPaid.setScale(8,BigDecimal.ROUND_HALF_UP);


               EthIncomeList ethIncomeList = ethIncomeListServic.selectEthIncomeListByProductDate(startDate,userCode);
               if(null == ethIncomeList){
                   EthIncomeList ethIncomeList1 = new EthIncomeList();
                   ethIncomeList1.setPaid(todayPaid.doubleValue());
                   ethIncomeList1.setProductDate(startDate);
                   ethIncomeList1.setBlockCount(blockCount);
                   ethIncomeList1.setCreateDate(dateFormat1.parse(dateFormat1.format(new Date())));
                   ethIncomeList1.setCurrentDifficulty(currentDifficulty.longValue());
                   ethIncomeList1.setComputingPowerRatio(computingPowerRatio.doubleValue());
                   ethIncomeList1.setHashRateCount(hashRateCount);
                   ethIncomeList1.setWeHashrateAvg(hashrate.doubleValue());
                   ethIncomeList1.setWholeNetworkCurrentHashrateAvg(currentHashrate.doubleValue());
                   ethIncomeList1.setRewardCount(rewardCount);
                   ethIncomeList1.setUserCode(userCode);
                   ethIncomeList1.setMiningHours(24.00);

                   Integer flag = ethIncomeListServic.insert(ethIncomeList1);
                   if(flag>0){
                       logger.debug("每日收益记录成功");
                   }else{
                       logger.error("每日收益记录失败");
                   }
               }
           }

        } catch (Exception e) {
            e.printStackTrace();
        }



        logger.debug("每天的任务收益记录（定时器结束）");
    }
}